<template>
  <div class="app-container">
    <!-- 引入物料选择器组件 -->
    <MaterialSelector 
      ref="materialSelectorRef" 
      v-model:visible="materialSelectorVisible" 
      @select="handleMaterialSelected" 
    />
    
    <!-- 引入纯粹的仓库选择器组件 -->
    <WarehouseOnlySelector
      ref="warehouseSelectorRef"
      v-model:visible="warehouseSelectorVisible"
      @select="handleWarehouseSelected"
    />

    <!-- 引入工单选择器组件 -->
    <WorkorderSelector
      ref="workorderSelectorRef"
      v-model:visible="workorderSelectorVisible"
      :filters="{ status: '1' || status === '2' }" 
      @select="handleWorkorderSelected"
    />

    <!-- 引入库位选择器组件 -->
    <LocationSelectorWithInventory
      ref="locationSelectorRef"
      v-model:visible="locationSelectorVisible"
      :isOutbound="true"
      :preSelectedWarehouseId="currentWarehouseId"
      @select="handleLocationSelected"
      @selectWithMaterial="handleLocationAndMaterialSelected"
    />

    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="申请编号" prop="applyCode">
        <el-input
          v-model="queryParams.applyCode"
          placeholder="请输入申请编号"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请类型" prop="applyType">
        <el-select v-model="queryParams.applyType" placeholder="请选择申请类型" clearable>
          <el-option
            v-for="dict in mvm_outbound_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option
            v-for="dict in apply_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="工单ID" prop="orderId">
        <el-input
          v-model="queryParams.orderId"
          placeholder="请输入工单ID"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="申请人" prop="applyUserId">
        <el-select
          v-model="queryParams.applyUserId"
          placeholder="请选择申请人"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeApplyTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="审核人" prop="auditUserId">
        <el-select
          v-model="queryParams.auditUserId"
          placeholder="请选择审核人"
          clearable
          @keyup.enter="handleQuery"
        >
          <el-option
            v-for="item in userOptions"
            :key="item.userId"
            :label="item.userName"
            :value="item.userId"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="审核时间" style="width: 308px">
        <el-date-picker
          v-model="daterangeAuditTime"
          value-format="YYYY-MM-DD"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['tas:MaterialOutboundApply:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="MaterialOutboundApplyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="申请ID" align="center" prop="applyId" />
      <el-table-column label="申请编号" align="center" prop="applyCode" />
      <el-table-column label="申请类型" align="center" prop="applyType">
        <template #default="scope">
          <dict-tag :options="mvm_outbound_type" :value="scope.row.applyType"/>
        </template>
      </el-table-column>
      <el-table-column label="申请人" align="center" prop="applyUserName" />
      <el-table-column label="申请时间" align="center" prop="applyTime" width="180" />
      <el-table-column label="工单编号" align="center" prop="orderCode" />
      <el-table-column label="审核人" align="center" prop="auditUserName" />
      <el-table-column label="审核时间" align="center" prop="auditTime" width="180" />
      <el-table-column label="审核意见" align="center" prop="auditOpinion" />
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="状态" align="center" prop="status">
        <template #default="scope">
          <dict-tag :options="apply_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button 
            link 
            type="primary" 
            icon="View" 
            @click="handleUpdate(scope.row)" 
            v-hasPermi="['sks:MaterialOutboundAudit:edit']"
            v-if="scope.row.status === '0'"
          >审核</el-button>
          
          <el-button 
            link 
            type="info" 
            icon="View" 
            @click="handleView(scope.row)" 
            v-else
          >查看</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改物料出库申请对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="MaterialOutboundApplyRef" :model="form" :rules="rules" label-width="100px" :inline="true">
        <el-form-item label="申请编号" prop="applyCode">
          <el-input v-model="form.applyCode" placeholder="申请编号" disabled/>
        </el-form-item>
        <el-form-item label="申请类型" prop="applyType">
          <el-select v-model="form.applyType" placeholder="请选择申请类型" @change="handleApplyTypeChange" disabled>
            <el-option
              v-for="dict in mvm_outbound_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" disabled>
            <el-option
              v-for="dict in apply_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="工单" prop="orderId" v-if="String(form.applyType) === '1' || String(form.applyType) === '2'">
          <div class="bom-xuanze">
            <el-input 
              v-model="form.orderCode" 
              placeholder="请选择工单" 
              readonly 
              class="bom-input"
            >
              <template #append>
                <el-button @click="openWorkorderSelector" disabled>选择</el-button>
              </template>
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="申请人" prop="applyUserId">
          <el-select v-model="form.applyUserId" placeholder="请选择申请人" filterable disabled>
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="申请时间" prop="applyTime">
          <el-date-picker clearable
            v-model="form.applyTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择申请时间"
            disabled
          >
          </el-date-picker>
        </el-form-item>
        
        <!-- 添加审核人表单项 -->
        <el-form-item label="审核人" prop="auditUserId" v-if="form.applyId && !isAudit">
          <el-input v-model="form.auditUserName" placeholder="审核人" disabled />
        </el-form-item>
        <el-form-item label="审核人" prop="auditUserId" v-if="isAudit">
          <el-select 
            v-model="form.auditUserId" 
            placeholder="请选择审核人" 
            filterable
          >
            <el-option
              v-for="item in userOptions"
              :key="item.userId"
              :label="item.userName"
              :value="item.userId"
            />
          </el-select>
        </el-form-item>
        
        <!-- 添加审核时间表单项 -->
        <el-form-item label="审核时间" prop="auditTime" v-if="form.applyId && !isAudit && form.auditTime">
          <el-input v-model="form.auditTime" placeholder="审核时间" disabled />
        </el-form-item>
        
        <!-- 添加审核意见表单项 -->
        <el-form-item label="审核意见" prop="auditOpinion" v-if="isAudit">
          <el-input 
            v-model="form.auditOpinion" 
            type="textarea" 
            placeholder="请输入审核意见" 
            :rows="3"
            style="width: 300px;"
          />
        </el-form-item>
        <el-form-item label="审核意见" prop="auditOpinion" v-if="form.applyId && !isAudit && form.auditOpinion">
          <el-input v-model="form.auditOpinion" type="textarea" placeholder="审核意见" disabled :rows="3" style="width: 300px;"/>
        </el-form-item>
        
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" disabled/>
        </el-form-item>
        
        <!-- 工单所需物料清单展示 -->
        <div v-if="workorderMaterials.length > 0 && (form.applyType === '1' || form.applyType === '2')" class="materials-container">
          <el-divider content-position="center">工单所需物料清单</el-divider>
          <el-table 
            :data="workorderMaterials" 
            border 
            :header-cell-style="{background:'#f7f7f7'}"
            max-height="300px"
          >
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="物料编码" prop="materialCode" width="120" align="center" />
            <el-table-column label="物料名称" prop="materialName" width="150" align="center" />
            <el-table-column label="规格型号" prop="specification" width="120" align="center" />
            <el-table-column label="所需数量" prop="quantity" width="80" align="center">
              <template #default="scope">
                <span>{{ calculateNeededQuantity(scope.row.quantity) }}</span>
              </template>
            </el-table-column>
            <el-table-column label="单位" prop="unit" width="80" align="center" />
            <el-table-column label="来源" prop="source" width="100" align="center">
              <template #default="scope">
                <el-tag type="info">{{ scope.row.source || '工单' }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="关键物料" prop="isKeyMaterial" width="80" align="center">
              <template #default="scope">
                <el-tag :type="scope.row.isKeyMaterial === '1' ? 'danger' : 'info'">
                  {{ scope.row.isKeyMaterial === '1' ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
        
        <el-divider content-position="center">出库物料明细</el-divider>
        <el-row :gutter="10" class="mb8" v-if="!isAudit">
        </el-row>
        <el-table :data="materialOutboundApplyDetailList" :row-class-name="rowMaterialOutboundApplyDetailIndex" @selection-change="handleMaterialOutboundApplyDetailSelectionChange" ref="materialOutboundApplyDetail">
          <el-table-column label="序号" align="center" prop="index" width="50"/>
          <el-table-column label="物料" prop="materialId" width="130">
            <template #default="scope">
              <div class="wuliao-xuanze">
                <el-input 
                  v-model="scope.row.materialName" 
                  placeholder="请选择物料" 
                  readonly 
                  class="wuliao-input"
                  disabled
                >
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="数量" align="center" prop="quantity" width="100">
          </el-table-column>
          <el-table-column label="单位" align="center" prop="unit" width="60" />
          <el-table-column label="仓库" prop="warehouseId" width="150">
            <template #default="scope">
              <div class="cangku-xuanze">
                <el-input 
                  v-model="scope.row.warehouseName" 
                  placeholder="请选择仓库" 
                  readonly 
                  class="cangku-input"
                  disabled
                >
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库位" prop="locationId" width="180">
            <template #default="scope">
              <div class="location-xuanze">
              <el-input
                v-model="scope.row.locationName"
                  placeholder="请选择库位" 
                  readonly 
                  class="location-input"
                disabled
                >
                </el-input>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="库位可用数量" prop="availableQuantity" width="120" align="center">
            <template #default="scope">
              <span v-if="scope.row.availableQuantity !== undefined">{{ scope.row.availableQuantity }}</span>
              <el-button 
                v-else-if="scope.row.locationId" 
                size="small" 
                type="primary" 
                @click="loadLocationInventory(scope.row)" 
                icon="Refresh"
                :disabled="isAudit"
              >加载</el-button>
              <span v-else>-</span>
            </template>
          </el-table-column>
          <el-table-column label="备注" prop="remark" width="150">
            <template #default="scope">
              <el-input v-model="scope.row.remark" type="textarea" placeholder="请输入备注" :disabled="isAudit" />
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <template v-if="isAudit">
            <el-button type="success" @click="handleAuditPass">通 过</el-button>
            <el-button type="danger" @click="handleAuditReject">驳 回</el-button>
          </template>
          <el-button @click="cancel">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>


<script setup name="MaterialOutboundApply">
import { 
  listMaterialOutboundApply, 
  getMaterialOutboundApply, 
  delMaterialOutboundApply, 
  addMaterialOutboundApply, 
  updateMaterialOutboundApply,
  listUserAll,
  listMaterial, 
  listWarehouse, 
  listLocation 
} from "@/api/tas/MaterialOutboundApply";
import { listInventory, updateInventory, delInventory } from "@/api/mwm/inventory";
import { getLocation, updateLocation } from "@/api/wms/location";
import request from '@/utils/request';
import MaterialSelector from "@/components/MaterialSelector/index.vue";
import WarehouseOnlySelector from "@/components/WarehouseSelector/WarehouseOnlySelector.vue";
import WorkorderSelector from "@/components/WorkorderSelector/index.vue";
import { getWorkorder } from "@/api/pm/workorder";
import { getBom } from "@/api/pm/bom";  // 导入获取BOM的API
import { getPlan } from "@/api/pm/plan"; // 导入获取计划的API
import { getMaterial, updateMaterial } from "@/api/mwm/material"; // 导入物料查询API
import LocationSelectorWithInventory from "@/components/WarehouseLocationSelector/LocationSelectorWithInventory.vue";

const { proxy } = getCurrentInstance();
const { mvm_outbound_type, apply_status } = proxy.useDict('mvm_outbound_type', 'apply_status');

const MaterialOutboundApplyList = ref([]);
const materialOutboundApplyDetailList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const checkedMaterialOutboundApplyDetail = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const daterangeApplyTime = ref([]);
const daterangeAuditTime = ref([]);

// 用户选项
const userOptions = ref([]);

// 添加工单物料清单变量
const workorderMaterials = ref([]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    applyCode: null,
    applyType: null,
    status: null,
    orderId: null,
    applyUserId: null,
    applyTime: null,
    auditUserId: null,
    auditTime: null,
  },
  rules: {
    applyCode: [{ required: true, message: "申请编号不能为空", trigger: "blur" }],
    applyType: [{ required: true, message: "申请类型不能为空", trigger: "change" }],
    status: [{ required: true, message: "状态不能为空", trigger: "change" }],
    orderId: [{ 
      required: true, 
      message: "工单/BOM不能为空", 
      trigger: "change",
      validator: (rule, value, callback) => {
        if ((form.value.applyType === '1' || form.value.applyType === '2') && !value) {
          callback(new Error("生产领料/生产备料需要选择工单/BOM"));
        } else {
          callback();
        }
      }
    }],
    applyTime: [{ required: true, message: "申请时间不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

// 物料选择器相关变量
const materialSelectorVisible = ref(false);
const materialSelectorRef = ref(null);
const currentEditingIndex = ref(-1); // 记录当前编辑的行索引

// 仓库选择器相关变量
const warehouseSelectorVisible = ref(false);
const warehouseSelectorRef = ref(null);
const currentEditingType = ref(''); 

// 工单选择器相关变量
const workorderSelectorVisible = ref(false);
const workorderSelectorRef = ref(null);

// 库位选择器相关变量
const locationSelectorVisible = ref(false);
const locationSelectorRef = ref(null);
const currentWarehouseId = ref(null);

// 在script部分添加isAudit变量
const isAudit = ref(false);

/** 查询物料出库申请列表 */
function getList() {
  loading.value = true;
   let params = proxy.addDateRange(queryParams.value, daterangeApplyTime.value, "ApplyTime");
  // 再添加审核时间范围
  params = proxy.addDateRange(params, daterangeAuditTime.value, "AuditTime");
  listMaterialOutboundApply(params).then(response => {
    MaterialOutboundApplyList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 添加生成申请编号的函数
function generateApplyCode() {
  const date = new Date();
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  const dateStr = `${year}${month}${day}`;
  
  const randomNum = Math.floor(1000 + Math.random() * 9000);
  
  return `MOA${dateStr}${randomNum}`;
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    applyId: null,
    applyCode: null,
    applyType: null,
    status: "4", // 待提交状态
    orderId: null,
    orderName: null,
    applyUserId: null,
    applyTime: null,
    auditUserId: null,
    auditTime: null,
    auditOpinion: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  materialOutboundApplyDetailList.value = [];
  workorderMaterials.value = []; // 清空工单物料清单
  proxy.resetForm("MaterialOutboundApplyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeApplyTime.value = [];
  daterangeAuditTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.applyId);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}


/** 修改按钮操作 */
function handleUpdate(row) {
  const _applyId = row.applyId || ids.value[0];
  loading.value = true;
  
  getMaterialOutboundApply(_applyId).then(response => {
    loading.value = false;
    if (response.code === 200) {
      // 处理表单数据
      form.value = response.data;
      
      // 确保工单信息完整
      if (form.value.orderId) {
        // 如果有工单ID但没有工单编号，获取工单详情
        if (!form.value.orderCode || !form.value.orderName) {
          getWorkorder(form.value.orderId).then(res => {
            if (res.code === 200 && res.data) {
              form.value.orderCode = res.data.orderCode;
              form.value.orderName = res.data.orderName || res.data.orderCode;
            }
          }).catch(err => {
            console.error("获取工单详情失败:", err);
          });
        }
      }
      
      // 处理明细列表
      if (response.data.materialOutboundApplyDetailList) {
        // 将明细列表转换为数组
        materialOutboundApplyDetailList.value = response.data.materialOutboundApplyDetailList || [];
        
        // 如果有工单ID，加载工单所需物料信息用于展示
        if (form.value.orderId && (form.value.applyType === '1' || form.value.applyType === '2')) {
          loadWorkorderMaterials(form.value.orderId);
        }
        
        // 补充物料详细信息，确保显示物料名称、规格等完整信息
        completeMaterialDetailsForList();
      } else {
        materialOutboundApplyDetailList.value = [];
      }
    
      open.value = true;
      title.value = "审核出库申请";
      isAudit.value = true; // 标记为审核模式
    }
  });
}

/** 查看按钮操作 */
function handleView(row) {
  const _applyId = row.applyId || ids.value[0];
  loading.value = true;
  
  getMaterialOutboundApply(_applyId).then(response => {
    loading.value = false;
    if (response.code === 200) {
      // 处理表单数据
      form.value = response.data;
      
      // 确保工单信息完整
      if (form.value.orderId) {
        // 如果有工单ID但没有工单编号，获取工单详情
        if (!form.value.orderCode || !form.value.orderName) {
          getWorkorder(form.value.orderId).then(res => {
            if (res.code === 200 && res.data) {
              form.value.orderCode = res.data.orderCode;
              form.value.orderName = res.data.orderName || res.data.orderCode;
            }
          }).catch(err => {
            console.error("获取工单详情失败:", err);
          });
        }
      }
      
      // 处理明细列表
      if (response.data.materialOutboundApplyDetailList) {
        // 将明细列表转换为数组
        materialOutboundApplyDetailList.value = response.data.materialOutboundApplyDetailList || [];
        
        // 如果有工单ID，加载工单所需物料信息用于展示
        if (form.value.orderId && (form.value.applyType === '1' || form.value.applyType === '2')) {
          loadWorkorderMaterials(form.value.orderId);
        }
        
        // 补充物料详细信息，确保显示物料名称、规格等完整信息
        completeMaterialDetailsForList();
      } else {
        materialOutboundApplyDetailList.value = [];
      }
    
      open.value = true;
      title.value = "查看出库申请";
      isAudit.value = false; // 标记为查看模式
    }
  });
}

// 修改审核通过方法
function handleAuditPass() {
  if (!form.value.auditUserId) {
    proxy.$modal.msgError("请选择审核人");
    return;
  }
  
  // 检查明细表格中每一行是否有足够的库存
  let hasInventoryError = false;
  materialOutboundApplyDetailList.value.forEach(detail => {
    if (!detail.availableQuantity) {
      proxy.$modal.msgError(`请先加载物料 "${detail.materialName}" 在库位 "${detail.locationName}" 的可用库存数量`);
      hasInventoryError = true;
      return;
    }
    
    const outboundQuantity = parseFloat(detail.quantity) || 0;
    const availableQuantity = parseFloat(detail.availableQuantity) || 0;
    
    if (outboundQuantity > availableQuantity) {
      proxy.$modal.msgError(`物料 "${detail.materialName}" 在库位 "${detail.locationName}" 的库存不足，申请出库 ${outboundQuantity}，但可用库存只有 ${availableQuantity}`);
      hasInventoryError = true;
    }
  });
  
  if (hasInventoryError) {
    return;
  }
  
  proxy.$modal.confirm('确认通过该出库申请吗？将从库存中扣减相应数量').then(function() {
    // 显示加载中
    proxy.$modal.loading("正在处理出库申请...");
    
    return getMaterialOutboundApply(form.value.applyId).then(response => {
      const completeData = response.data;
      
      // 检查是否有物料明细
      if (!completeData.materialOutboundApplyDetailList || completeData.materialOutboundApplyDetailList.length === 0) {
        return proxy.$modal.msgError("出库申请没有物料明细，无法进行出库操作");
      }
      
      // 1. 处理所有明细的库存变更和库位容量更新
      const processPromises = completeData.materialOutboundApplyDetailList.map(detail => {
        return processOutboundDetail(detail);
      });
      
      // 等待所有处理完成
      return Promise.all(processPromises).then(() => {
        // 2. 全部处理完成后，更新出库申请状态
        const updateObj = {
          applyId: form.value.applyId,
          status: '1',  // 已审核
          auditOpinion: form.value.auditOpinion,
          auditUserId: form.value.auditUserId,
          auditTime: new Date(),
          materialOutboundApplyDetailList: completeData.materialOutboundApplyDetailList  // 使用后端返回的完整明细数据
        };
        
        return updateMaterialOutboundApply(updateObj);
      });
    });
  }).then(() => {
    proxy.$modal.closeLoading(); // 关闭加载中
    open.value = false;
    getList();
    proxy.$modal.msgSuccess("审核通过成功，库存和库位已更新");
  }).catch((error) => {
    proxy.$modal.closeLoading(); // 关闭加载中
    console.error("出库处理失败", error);
    proxy.$modal.msgError("出库处理失败：" + (error.message || "未知错误"));
  });
}

// 处理出库明细项的函数
function processOutboundDetail(detail) {
  // 1. 获取库位信息以更新已用容量
  return getLocation(detail.locationId).then(locationRes => {
    const locationData = locationRes.data;
    if (!locationData) {
      return Promise.reject(new Error(`找不到库位信息，ID: ${detail.locationId}`));
    }
    
    // 计算出库后的已用容量 - 直接使用出库数量减少容量
    const currentUsedCapacity = parseFloat(locationData.usedCapacity) || 0;
    const outboundQuantity = parseFloat(detail.quantity) || 0;
    const newUsedCapacity = Math.max(0, currentUsedCapacity - outboundQuantity);
    
    // 2. 更新库位已用容量
    return updateLocation({
      locationId: detail.locationId,
      usedCapacity: newUsedCapacity.toFixed(2)
    }).then(() => {
      // 3. 查询该库位该物料的库存记录
      return listInventory({
        materialId: detail.materialId,
        locationId: detail.locationId
      });
    }).then(inventoryRes => {
      const inventoryList = inventoryRes.rows || [];
      if (inventoryList.length === 0) {
        return Promise.reject(new Error(`物料 ${detail.materialName} 在库位 ${detail.locationName} 没有库存记录`));
      }
      
      const inventory = inventoryList[0];
      const currentQuantity = parseFloat(inventory.quantity) || 0;
      const outboundQuantity = parseFloat(detail.quantity) || 0;
      const newQuantity = Math.max(0, currentQuantity - outboundQuantity);
      
      // 4. 更新库存记录
      let inventoryPromise;
      if (newQuantity > 0) {
        // 数量大于0，更新库存
        inventoryPromise = updateInventory({
          inventoryId: inventory.inventoryId,
          quantity: newQuantity.toFixed(2)
        });
      } else {
        // 数量为0，删除库存记录
        inventoryPromise = delInventory(inventory.inventoryId);
      }
      
      // 5. 更新物料管理中的总库存数量
      return inventoryPromise.then(() => {
        return getMaterial(detail.materialId).then(materialRes => {
          if (materialRes.code === 200 && materialRes.data) {
            const materialData = materialRes.data;
            const currentStock = parseFloat(materialData.currentStock) || 0;
            const newStock = Math.max(0, currentStock - outboundQuantity);
            
            return updateMaterial({
              materialId: materialData.materialId,
              currentStock: Math.floor(newStock) // 转换为整数以避免JSON解析错误
            });
          }
        });
      });
    });
  });
}

// 修改审核驳回方法
function handleAuditReject() {
  if (!form.value.auditUserId) {
    proxy.$modal.msgError("请选择审核人");
    return;
  }
  
  if (!form.value.auditOpinion) {
    proxy.$modal.msgError("驳回时必须填写审核意见");
    return;
  }
  
  proxy.$modal.confirm('确认驳回该出库申请吗？').then(function() {
    return getMaterialOutboundApply(form.value.applyId).then(response => {
      const completeData = response.data;
      
      const updateObj = {
        applyId: form.value.applyId,
        status: '2',  // 已驳回
        auditOpinion: form.value.auditOpinion,
        auditUserId: form.value.auditUserId,
        auditTime: new Date(),
        materialOutboundApplyDetailList: completeData.materialOutboundApplyDetailList  // 使用后端返回的完整明细数据
      };
      
      return updateMaterialOutboundApply(updateObj);
    });
  }).then(() => {
    open.value = false;
    getList();
    proxy.$modal.msgSuccess("审核驳回成功");
  }).catch(() => {});
}

// 添加计算所需物料数量的函数
function calculateNeededQuantity(unitQuantity) {
  // 确保输入是有效数字，否则返回默认值
  if (!unitQuantity || isNaN(parseFloat(unitQuantity))) return '1.00';
  
  // 返回格式化后的数值
  return parseFloat(unitQuantity).toFixed(2);
}

// 补充物料完整信息的函数
async function completeMaterialInfo(materialsList) {
  if (!materialsList || materialsList.length === 0) {
    return [];
  }
  
  try {
    // 使用Promise.all并行处理所有物料查询
    const detailsWithInfo = await Promise.all(
      materialsList.map(async material => {
        // 如果物料信息不完整，尝试获取完整信息
        if (!material.materialName || !material.materialCode || !material.specification) {
          try {
            const materialRes = await getMaterial(material.materialId);
            if (materialRes.code === 200 && materialRes.data) {
              // 合并物料信息
              return {
                ...material,
                materialName: materialRes.data.materialName || material.materialName || '',
                materialCode: materialRes.data.materialCode || material.materialCode || '',
                specification: materialRes.data.specification || material.specification || '',
                unit: materialRes.data.unit || material.unit || ''
              };
            }
          } catch (err) {
            console.error("获取物料信息失败:", err);
          }
        }
        return material;
      })
    );
    
    return detailsWithInfo;
  } catch (err) {
    console.error("补充物料信息失败:", err);
    return materialsList;
  }
}

// 补充明细列表中物料的详细信息
async function completeMaterialDetailsForList() {
  if (materialOutboundApplyDetailList.value.length === 0) return;
  
  try {
    // 获取所有物料的ID列表
    const materialIds = materialOutboundApplyDetailList.value
      .map(item => item.materialId)
      .filter(id => id); // 过滤掉空值
    
    // 获取所有仓库的ID列表
    const warehouseIds = materialOutboundApplyDetailList.value
      .map(item => item.warehouseId)
      .filter(id => id); // 过滤掉空值
    
    // 获取所有库位的ID列表
    const locationIds = materialOutboundApplyDetailList.value
      .map(item => item.locationId)
      .filter(id => id); // 过滤掉空值
    
    // 创建物料ID到明细项的映射，用于更新
    const detailMap = new Map();
      materialOutboundApplyDetailList.value.forEach(item => {
        if (item.materialId) {
        detailMap.set(item.materialId, item);
      }
    });
    
    // 1. 补充物料信息
    if (materialIds.length > 0) {
      // 获取所有物料详情
      const response = await listMaterial();
      if (response.code === 200 && response.data) {
        // 筛选出需要的物料信息
        const materialsData = response.data.filter(material => 
          materialIds.includes(material.materialId)
        );
        
        // 更新明细中的物料信息
        materialsData.forEach(material => {
          const detailItem = detailMap.get(material.materialId);
          if (detailItem) {
            // 更新物料详细信息
            detailItem.materialName = detailItem.materialName || material.materialName;
            detailItem.materialCode = detailItem.materialCode || material.materialCode;
            detailItem.specification = detailItem.specification || material.specification;
            detailItem.unit = detailItem.unit || material.unit;
        }
      });
    }
    }
    
    // 2. 补充仓库信息
    if (warehouseIds.length > 0) {
      const warehouseResponse = await listWarehouse();
      if (warehouseResponse.code === 200 && warehouseResponse.data) {
        const warehousesData = warehouseResponse.data;
        
        // 创建仓库ID到仓库信息的映射
        const warehouseMap = new Map();
        warehousesData.forEach(warehouse => {
          warehouseMap.set(warehouse.warehouseId, warehouse);
        });
        
        // 更新明细中的仓库信息
      materialOutboundApplyDetailList.value.forEach(item => {
        if (item.warehouseId) {
            const warehouse = warehouseMap.get(item.warehouseId);
          if (warehouse) {
              item.warehouseName = item.warehouseName || warehouse.warehouseName;
          }
        }
      });
    }
    }
    
    // 3. 补充库位信息
    if (locationIds.length > 0) {
      const locationResponse = await listLocation();
      if (locationResponse.code === 200 && locationResponse.data) {
        const locationsData = locationResponse.data;
        
        // 创建库位ID到库位信息的映射
        const locationMap = new Map();
        locationsData.forEach(location => {
          locationMap.set(location.locationId, location);
        });
        
        // 更新明细中的库位信息
      materialOutboundApplyDetailList.value.forEach(item => {
        if (item.locationId) {
            const location = locationMap.get(item.locationId);
          if (location) {
              item.locationName = item.locationName || location.locationName;
          }
        }
      });
    }
    }
    
    // 4. 加载每个库位的库存可用数量
    const loadPromises = materialOutboundApplyDetailList.value
      .filter(item => item.materialId && item.locationId)
      .map(item => loadLocationInventory(item));
    
    await Promise.all(loadPromises);
    
  } catch (err) {
    console.error("补充物料详情失败:", err);
  }
}

// 加载库位库存可用数量
function loadLocationInventory(item) {
  return new Promise((resolve, reject) => {
  if (!item.materialId || !item.locationId) {
      resolve();
    return;
  }
  
  // 查询库存信息
  listInventory({
    materialId: item.materialId,
    locationId: item.locationId
  }).then(response => {
    if (response.code === 200 && response.rows && response.rows.length > 0) {
      const inventory = response.rows[0];
        // 更新可用数量
        item.availableQuantity = inventory.quantity || 0;
    } else {
      item.availableQuantity = 0; // 如果没有库存记录，设为0
    }
      resolve();
    }).catch(err => {
      console.error("获取库存信息失败:", err);
    item.availableQuantity = 0;
      resolve();
    });
  });
}

// 加载工单所需物料信息
function loadWorkorderMaterials(orderId) {
  if (!orderId) return;
  
  getWorkorder(orderId).then(result => {
    if (result.code === 200 && result.data) {
      const workorderData = result.data;
      
      // 尝试获取工单物料清单
      if (workorderData.materialList && workorderData.materialList.length > 0) {
        // 保存到工单物料列表用于展示
        completeMaterialInfo(workorderData.materialList).then(completeList => {
          workorderMaterials.value = completeList.map(material => ({
            ...material,
            materialCode: material.materialCode || '',
            materialName: material.materialName || '',
            specification: material.specification || '',
            isKeyMaterial: material.isKeyMaterial || '0',
            source: '工单',
            // 确保数量是有效值
            quantity: material.quantity && parseFloat(material.quantity) > 0 
              ? parseFloat(material.quantity).toFixed(2) 
              : '1.00'
          }));
        });
      } 
      // 如果没有直接关联物料清单，尝试通过计划获取BOM物料清单
      else if (workorderData.planId) {
        getPlan(workorderData.planId).then(res => {
          if (res.code === 200 && res.data && res.data.bomId) {
            getBom(res.data.bomId).then(bomRes => {
              if (bomRes.code === 200 && bomRes.data && bomRes.data.bomDetailList) {
                // 确保有计划数量，如果没有则使用默认值1
                const planQuantity = res.data.planQuantity || res.data.productionQuantity || workorderData.quantity || 1;
                
                const bomMaterials = bomRes.data.bomDetailList.map(material => ({
                  ...material,
                  quantity: calculateMaterialQuantity(material.quantity || material.unitQuantity, planQuantity),
                  materialCode: material.materialCode || '',
                  materialName: material.materialName || '',
                  specification: material.specification || '',
                  isKeyMaterial: material.isKeyMaterial || '0',
                  source: '计划BOM'
                }));
                
                completeMaterialInfo(bomMaterials).then(completeList => {
                  workorderMaterials.value = completeList;
                });
              }
            });
          }
        });
      }
    }
  }).catch(err => {
    console.error("获取工单信息失败:", err);
  });
}


/** 物料出库申请明细序号 */
function rowMaterialOutboundApplyDetailIndex({ row, rowIndex }) {
  row.index = rowIndex + 1;
}



/** 复选框选中数据 */
function handleMaterialOutboundApplyDetailSelectionChange(selection) {
  checkedMaterialOutboundApplyDetail.value = selection.map(item => item.index)
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('tas/MaterialOutboundApply/export', {
    ...queryParams.value
  }, `MaterialOutboundApply_${new Date().getTime()}.xlsx`)
}


function handleWarehouseSelected(warehouse) {
  if (warehouse && currentEditingIndex.value >= 0) {
    const index = currentEditingIndex.value;
    
    materialOutboundApplyDetailList.value[index].warehouseId = warehouse.warehouseId;
    materialOutboundApplyDetailList.value[index].warehouseName = warehouse.warehouseName;
    
    // 清空原有库位信息，等待用户单独选择库位
      materialOutboundApplyDetailList.value[index].locationId = '';
      materialOutboundApplyDetailList.value[index].locationName = '';
      materialOutboundApplyDetailList.value[index].availableQuantity = undefined;
    
    currentEditingIndex.value = -1;
  }
}


function handleMaterialSelected(material) {
  if (material && currentEditingIndex.value >= 0 && currentEditingType.value === 'material') {
    const index = currentEditingIndex.value;
    materialOutboundApplyDetailList.value[index].materialId = material.materialId;
    materialOutboundApplyDetailList.value[index].materialName = material.materialName;
    materialOutboundApplyDetailList.value[index].unit = material.unit;
    
    // 如果已经有库位，刷新库存信息
    if (materialOutboundApplyDetailList.value[index].locationId) {
      loadLocationInventory(materialOutboundApplyDetailList.value[index]);
    }
    
    currentEditingIndex.value = -1;
    currentEditingType.value = '';
  }
}

// 打开工单选择器，排除已完成的工单
function openWorkorderSelector() {
  // 设置过滤条件，排除已完成状态的工单
  const filters = {
    status: ['1', '2'], // 只显示"待执行"和"执行中"状态的工单
    notStatus: '3'      // 排除"已完成"状态
  };
  
  // 如果组件支持设置过滤条件
  if (workorderSelectorRef.value.setFilters) {
    workorderSelectorRef.value.setFilters(filters);
  } else {
    // 如果没有setFilters方法，可以通过props传递
    workorderSelectorRef.value.filters = filters;
  }
  
  workorderSelectorRef.value.open();
}

// 计算物料数量（单位用量×生产数量）
function calculateMaterialQuantity(unitQuantity, productionQuantity) {
  // 确保参数有效，如果无效则使用默认值
  const qty1 = parseFloat(unitQuantity || 1);
  const qty2 = parseFloat(productionQuantity || 1);
  
  // 计算乘积并保留两位小数
  return (qty1 * qty2).toFixed(2);
}

function handleWorkorderSelected(result) {
  // 接收包含工单信息、计划信息和物料清单的结果
  if (result && result.workorder) {
    // 设置工单信息
    form.value.orderId = result.workorder.orderId;
    form.value.orderCode = result.workorder.orderCode;
    form.value.orderName = result.workorder.orderName || result.workorder.orderCode;
    
    // 检查工单是否直接关联了物料清单
    const materials = result.materialList || [];
    if (materials.length > 0) {
      // 保存工单物料清单用于展示，并补充物料完整信息
      proxy.$modal.msgWarning("正在获取物料详细信息...");
      completeMaterialInfo(materials).then(completeList => {
        workorderMaterials.value = completeList.map(material => ({
          ...material,
          materialCode: material.materialCode || '',
          materialName: material.materialName || '',
          specification: material.specification || '',
          isKeyMaterial: material.isKeyMaterial || '0',
          source: '工单',
          // 确保数量是有效值
          quantity: material.quantity && parseFloat(material.quantity) > 0 
            ? parseFloat(material.quantity).toFixed(2) 
            : '1.00'
        }));
        
      proxy.$modal.confirm('是否加载关联的物料清单？').then(() => {
        // 清空当前明细
        materialOutboundApplyDetailList.value = [];
        
        // 添加物料清单明细
          completeList.forEach(material => {
          const detailItem = {
            applyId: form.value.applyId || "",
            materialId: material.materialId,
            materialName: material.materialName,
            quantity: material.quantity,
            unit: material.unit,
            warehouseId: "",
            warehouseName: "",
            locationId: "",
            locationName: "",
            remark: material.source === '计划' 
              ? `来自计划物料清单` 
              : `来自工单${result.workorder.orderCode}物料清单`
          };
          
          materialOutboundApplyDetailList.value.push(detailItem);
        });
        
        proxy.$modal.msgSuccess("已加载物料清单");
      }).catch(() => {
          proxy.$modal.msgWarning("未加载物料清单");
        });
      }).catch(err => {
        console.error("补充物料信息失败:", err);
        proxy.$modal.msgError("获取物料详细信息失败");
      });
    } 
    // 2. 检查是否有关联计划，通过计划获取BOM物料清单
    else if (result.workorder.planId) {
      proxy.$modal.msgWarning("正在获取工单关联计划的物料清单...");
      getPlan(result.workorder.planId).then(res => {
        if (res.code === 200 && res.data && res.data.bomId) {
          // 获取BOM物料清单
          getBom(res.data.bomId).then(bomRes => {
            if (bomRes.code === 200 && bomRes.data && bomRes.data.bomDetailList && bomRes.data.bomDetailList.length > 0) {
              // 确保有计划数量，如果没有则使用默认值1
              const planQuantity = res.data.planQuantity || res.data.productionQuantity || result.workorder.quantity || 1;
              // 计算物料数量 = 单位用量 × 计划生产数量
              const bomMaterials = bomRes.data.bomDetailList.map(material => ({
                ...material,
                quantity: calculateMaterialQuantity(material.quantity || material.unitQuantity, planQuantity),
                materialCode: material.materialCode || '',
                materialName: material.materialName || '',
                specification: material.specification || '',
                isKeyMaterial: material.isKeyMaterial || '0',
                source: '计划BOM'
              }));
              
              // 补充物料完整信息
              completeMaterialInfo(bomMaterials).then(completeList => {
                workorderMaterials.value = completeList;
                
                proxy.$modal.confirm('已获取计划BOM物料清单，是否加载？').then(() => {
                  // 清空当前明细
                  materialOutboundApplyDetailList.value = [];
                  // 添加物料清单明细
                  completeList.forEach(material => {
                    const detailItem = {
                      applyId: form.value.applyId || "",
                      materialId: material.materialId,
                      materialName: material.materialName,
                      quantity: material.quantity,
                      unit: material.unit,
                      warehouseId: "",
                      warehouseName: "",
                      locationId: "",
                      locationName: "",
                      remark: `来自计划[${res.data.planCode}]BOM物料清单`
                    };
                    
                    materialOutboundApplyDetailList.value.push(detailItem);
                  });
                  
                  proxy.$modal.msgSuccess("已加载计划BOM物料清单");
                }).catch(() => {
                  proxy.$modal.msgWarning("未加载物料清单");
                });
              }).catch(err => {
                console.error("补充物料信息失败:", err);
                proxy.$modal.msgError("获取物料详细信息失败");
              });
            } else {
              workorderMaterials.value = [];
              proxy.$modal.msgWarning("未找到关联计划的BOM物料清单");
            }
          }).catch(err => {
            console.error("获取BOM失败:", err);
            workorderMaterials.value = [];
            proxy.$modal.msgError("获取BOM物料清单失败");
          });
        } else {
          workorderMaterials.value = [];
          proxy.$modal.msgWarning("此工单关联的计划未设置BOM");
        }
      }).catch(err => {
        console.error("获取计划失败:", err);
        workorderMaterials.value = [];
        proxy.$modal.msgError("获取关联计划失败");
      });
    }
    // 3. 检查工单是否直接关联了BOM
    else if (result.workorder.bomId) {
      proxy.$modal.msgWarning("正在获取工单关联BOM的物料清单...");
      getBom(result.workorder.bomId).then(bomRes => {
        if (bomRes.code === 200 && bomRes.data && bomRes.data.bomDetailList && bomRes.data.bomDetailList.length > 0) {
          // 确保工单数量有效，默认为1
          const workorderQuantity = result.workorder.quantity || result.workorder.planQuantity || 1;
          
          // 计算物料数量 = 单位用量 × 工单计划数量
          const bomMaterials = bomRes.data.bomDetailList.map(material => ({
            ...material,
            quantity: calculateMaterialQuantity(material.quantity || material.unitQuantity, workorderQuantity),
            materialCode: material.materialCode || '',
            materialName: material.materialName || '',
            specification: material.specification || '',
            isKeyMaterial: material.isKeyMaterial || '0',
            source: '工单BOM'
          }));
          
          // 补充物料完整信息
          completeMaterialInfo(bomMaterials).then(completeList => {
            workorderMaterials.value = completeList;
            
            proxy.$modal.confirm('已获取工单BOM物料清单，是否加载？').then(() => {
              // 清空当前明细
              materialOutboundApplyDetailList.value = [];
              
              // 添加物料清单明细
              completeList.forEach(material => {
                const detailItem = {
                  applyId: form.value.applyId || "",
                  materialId: material.materialId,
                  materialName: material.materialName,
                  quantity: material.quantity,
                  unit: material.unit,
                  warehouseId: "",
                  warehouseName: "",
                  locationId: "",
                  locationName: "",
                  remark: `来自工单[${result.workorder.orderCode}]BOM物料清单`
                };
                
                materialOutboundApplyDetailList.value.push(detailItem);
              });
              
              proxy.$modal.msgSuccess("已加载工单BOM物料清单");
            }).catch(() => {
              proxy.$modal.msgWarning("未加载物料清单");
            });
          }).catch(err => {
            console.error("补充物料信息失败:", err);
            proxy.$modal.msgError("获取物料详细信息失败");
          });
        } else {
          workorderMaterials.value = [];
          proxy.$modal.msgWarning("未找到关联的BOM物料清单");
        }
      }).catch(err => {
        console.error("获取BOM失败:", err);
        workorderMaterials.value = [];
        proxy.$modal.msgError("获取BOM物料清单失败");
      });
    } else {
      workorderMaterials.value = [];
      proxy.$modal.msgWarning("此工单未关联物料清单，请手动添加物料");
    }
  }
}

// 修改申请类型变更处理
function handleApplyTypeChange(val) {
  // 清空工单信息
  form.value.orderId = null;
  form.value.orderName = null;
  
  // 根据类型自动设置标题
  if (val === '1') {
    title.value = form.value.applyId ? "修改生产领料申请" : "添加生产领料申请";
  } else if (val === '2') {
    title.value = form.value.applyId ? "修改生产备料申请" : "添加生产备料申请";
  } else if (val === '3') {
    title.value = form.value.applyId ? "修改其他出库申请" : "添加其他出库申请";
  }
}

// 处理选择库位
function handleLocationSelected(location) {
  // 获取当前编辑的行索引
  const index = currentEditingIndex.value;
  if (index >= 0) {
    // 更新明细中的库位信息
    materialOutboundApplyDetailList.value[index].locationId = location.locationId;
    materialOutboundApplyDetailList.value[index].locationName = location.locationName;
    
    // 如果已选择了物料，加载该库位下此物料的库存数量
    if (materialOutboundApplyDetailList.value[index].materialId) {
      loadLocationInventory(materialOutboundApplyDetailList.value[index]);
    }
    
    currentEditingIndex.value = -1;
  }
}

// 处理选择库位并选择物料（通过库存选择）
function handleLocationAndMaterialSelected(result) {
  // 获取当前编辑的行索引
  const index = currentEditingIndex.value;
  if (index >= 0 && result.location && result.material) {
    // 确保物料ID有效
    if (!result.material.materialId) {
      proxy.$modal.msgError("物料数据不完整，无法选择");
      return;
    }

    // 更新库位信息
    materialOutboundApplyDetailList.value[index].locationId = result.location.locationId;
    materialOutboundApplyDetailList.value[index].locationName = result.location.locationName;
    
    // 检查当前行是否已有物料信息
    const currentRow = materialOutboundApplyDetailList.value[index];
    const hasMaterial = currentRow.materialId && currentRow.materialName;
    
    if (hasMaterial) {
      // 如果已有物料信息，仅更新可用数量
      // 加载该库位下此物料的库存数量
      loadLocationInventory(currentRow);
    } else {
      // 如果没有物料信息，则更新物料信息
      materialOutboundApplyDetailList.value[index].materialId = result.material.materialId;
      materialOutboundApplyDetailList.value[index].materialName = result.material.materialName;
      materialOutboundApplyDetailList.value[index].materialCode = result.material.materialCode;
      materialOutboundApplyDetailList.value[index].specification = result.material.specification;
      materialOutboundApplyDetailList.value[index].unit = result.material.unit;
      
      // 设置可用数量
      materialOutboundApplyDetailList.value[index].availableQuantity = result.material.quantity;
      
      // 默认出库数量设为可用数量，但不超过需求数量
      if (result.material.quantity > 0 && !materialOutboundApplyDetailList.value[index].quantity) {
        materialOutboundApplyDetailList.value[index].quantity = result.material.quantity;
      }
    }
    
    currentEditingIndex.value = -1;
  }
}

onMounted(() => {
  listUserAll().then(response => {
    userOptions.value = response.data;
  });
getList();
});
</script>

<style scoped>
.wuliao-xuanze,
.cangku-xuanze,
.bom-xuanze {
  display: flex;
  align-items: center;
  width: 100%;
}

.wuliao-input,
.cangku-input,
.bom-input {
  width: 100%;
}

/* 添加物料清单容器样式 */
.materials-container {
  margin-top: 15px;
  width: 100%;
}

.location-xuanze {
  display: flex;
  align-items: center;
  width: 100%;
}

.location-input {
  width: 100%;
}
</style>
